package com.zhuiyun.project.api.system.user.service.impl;

import com.zhuiyun.project.api.monitor.domain.server.Sys;
import com.zhuiyun.project.api.system.role.entity.SysRole;
import com.zhuiyun.project.api.system.role.mapper.SysRoleMapper;
import com.zhuiyun.project.api.system.role.service.SysRoleService;
import com.zhuiyun.project.api.system.user.entity.SysUser;
import com.zhuiyun.project.api.system.user.entity.SysUserRole;
import com.zhuiyun.project.api.system.user.mapper.SysUserMapper;
import com.zhuiyun.project.api.system.user.mapper.SysUserRoleMapper;
import com.zhuiyun.project.api.system.user.service.SysUserService;
import com.zhuiyun.project.common.constant.UserConstants;
import com.zhuiyun.project.common.errorCode.EmErrorCode;
import com.zhuiyun.project.common.response.CommonResult;
import com.zhuiyun.project.security.jwt.JWTConfig;
import com.zhuiyun.project.utils.*;
import com.zhuiyun.project.utils.pageUtil.MybatisPageHelper;
import com.zhuiyun.project.utils.pageUtil.PageRequest;
import com.zhuiyun.project.utils.pageUtil.PageResult;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName SysUserServiceImpl
 * @Description TODO
 * @Author Acer
 * @Date 2023/10/26 15:41
 **/
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    SysUserMapper userMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysRoleMapper roleMapper;


    /**
     * @Author hyp
     * @Description 用户详情分页查询
     * @Date 2023/10/30 9:21
     * @Return com.zhuiyun.project.common.response.CommonResult
     * @param pageRequest
     * @param user
     */
    @Override
    public PageResult listUsers(PageRequest pageRequest, SysUser user) {
        MybatisPageHelper.startPage(pageRequest);
        List<SysUser> list  = userMapper.listUsers(user);
        PageResult pageResult = MybatisPageHelper.getPageResult(list);
        return pageResult;
    }

    /**
     * @Author hyp
     * @Description 根据用户编号获取详情信息
     * @Date 2023/10/30 9:27
     * @Return com.zhuiyun.project.common.response.CommonResult
     * @param id
     */
    @Override
    public SysUser selectUserById(Integer id) {
        return userMapper.selectUserById(id);
    }

    /**
     * @Author hyp
     * @Description 根据用户编号删除用户
     * @Date 2023/10/30 9:31
     * @Return com.zhuiyun.project.common.response.CommonResult
     * @param userids
     */
    @Override
    @Transactional
    public CommonResult removeUserByIds(Integer[] userids) {
        for (Integer userid : userids) {
            checkUserAllowed(new SysUser(userid));
        }
        userRoleMapper.deleteUserRole(userids);
        int i =userMapper.removeUserByIds(userids);
        if (i>0){
            return CommonResult.ok(EmErrorCode.DELETE_OK);
        }else {
            return CommonResult.error(EmErrorCode.DELETE_ERROR);
        }
    }
    /**
      * @Author hyp
      * @Description 校验权限
      * @Date 2023/10/30 19:00
      * @Return void
      * @param user
    */
    @Override
    public void checkUserAllowed(SysUser user) {
        if (StringUtils.isNotNull(user.getId()) && user.isAdmin())
        {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    /**
     * @Author hyp
     * @Description 修改用户
     * @Date 2023/10/30 9:31
     * @Return com.zhuiyun.project.common.response.CommonResult
     * @param user
     */
    @Override
    @Transactional
    public int editUser(SysUser user) {
        Integer userId = user.getId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        return userMapper.editUser(user);
    }

    /**
     * @Author hyp
     * @Description 修改用户状态
     * @Date 2023/10/30 9:33
     * @Return com.zhuiyun.project.common.response.CommonResult
     * @param user
     */
    @Override
    public int changeStatusUser(SysUser user) {
        return userMapper.editUser(user);
    }

    /**
     * @Author hyp
     * @Description 校验用户名唯一
     * @Date 2023/10/30 9:24
     * @Return com.zhuiyun.project.common.response.CommonResult
     * @param user
     */
    @Override
    public boolean checkLoginNameUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getId()) ? -1L : user.getId();
        SysUser info = userMapper.checkLoginNameUnique(user.getLoginName());
        if (StringUtils.isNotNull(info) && userId.longValue() != info.getId().longValue()){
            return UserConstants.NOT_UNIQUE;
        }else {
            return UserConstants.UNIQUE;
        }
    }

    /**
     * @Author hyp
     * @Description 校验手机号唯一
     * @Date 2023/10/30 9:24
     * @Return com.zhuiyun.project.common.response.CommonResult
     * @param user
     */
    @Override
    public boolean checkPhoneUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getId()) ? -1L : user.getId();
        SysUser info = userMapper.checkPhoneUnique(user.getPhone());
        if (StringUtils.isNotNull(info) && userId.longValue() != info.getId().longValue()){
            return UserConstants.NOT_UNIQUE;
        }else {
            return UserConstants.UNIQUE;
        }
    }

    /**
     * @Author hyp
     * @Description 校验用户名唯一
     * @Date 2023/10/30 9:24
     * @Return com.zhuiyun.project.common.response.CommonResult
     * @param user
     */
    @Override
    public boolean checkEmailUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getId()) ? -1L : user.getId();
        SysUser info = userMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && userId.longValue() != info.getId().longValue()){
            return UserConstants.NOT_UNIQUE;
        }else {
            return UserConstants.UNIQUE;
        }
    }

    /**
     * @Author hyp
     * @Description 获得当前登录用户所拥有的角色
     * @Date 2023/10/30 19:06
     * @Return java.lang.String
     * @param loginName
     */
    @Override
    public String selectUserRoleGroup(String loginName) {
        List<SysRole> roles = roleMapper.selectRoleByLoginName(loginName);
        if (CollectionUtils.isEmpty(roles)){
            return StringUtils.EMPTY;
        }else {
            return roles.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
        }
    }

    /**
     * @Author hyp
     * @Description 修改个人基本信息
     * @Date 2023/10/30 9:42
     * @Return com.zhuiyun.project.common.response.CommonResult
     * @param user
     */
    @Override
    public int updateProfile(SysUser user) {

        return userMapper.editUser(user);
    }

    /**
     * @Author hyp
     * @Description 修改密码
     * @Date 2023/10/30 9:44
     * @Return com.zhuiyun.project.common.response.CommonResult
     * @param userId
     * @param encryptPassword
     */
    @Override
    public int resetUserPwd(Integer userId, String encryptPassword) {
        return userMapper.resetUser(userId,encryptPassword);
    }

    /**
     * @Author hyp
     * @Description  修改用户头像
     * @Date 2023/10/30 13:42
     * @Return com.zhuiyun.project.common.response.CommonResult
     * @param avatarId
     * @param id
     */
    @Override
    public int updateAvatarId(String avatarId, Integer id) {

        return userMapper.updateAvatarId(avatarId,id);
    }

    /**
      * @Author hyp
      * @Description 根据手机号查询用户信息
      * @Date 2023/10/30 19:45
      * @Return com.zhuiyun.project.api.system.user.entity.SysUser
      * @param phoneAccount
    */
    @Override
    public SysUser getUserByPhoneAccount(String phoneAccount) {
        if (StringUtils.isNotNull(phoneAccount)){
            Example example = new Example(SysUser.class);
            example.createCriteria().andEqualTo("phone",phoneAccount);
            return userMapper.selectOneByExample(example);
        }
        return null;
    }

    /**
     * @Author hyp
     * @Description 根据邮箱查询用户信息
     * @Date 2023/10/30 19:45
     * @Return com.zhuiyun.project.api.system.user.entity.SysUser
     * @param emailAccount
     */
    @Override
    public SysUser getUserByEmailAccount(String emailAccount) {
        if (StringUtils.isNotNull(emailAccount)){
            Example example = new Example(SysUser.class);
            example.createCriteria().andEqualTo("email",emailAccount);
            return userMapper.selectOneByExample(example);
        }else {
            return null;
        }
    }

    /**
     * @Author hyp
     * @Description 根据登录名查询用户信息
     * @Date 2023/10/30 19:51
     * @Return com.zhuiyun.project.api.system.user.entity.SysUser
     * @param loginName
     */
    @Override
    public SysUser getUserByLoginName(String loginName) {
        SysUser list  = userMapper.getUserByLoginName(loginName);
        return list;
    }

    /**
      * @Author hyp
      * @Description 更新登录成功后更新用户信息
      * @Date 2023/10/30 19:58
      * @Return void
      * @param sysUser
    */
    @Override
    public void updateUserByLogin(SysUser sysUser) {
        if(ObjectUtils.isNotEmpty(sysUser)&&ObjectUtils.isNotEmpty(sysUser.getId())){
            userMapper.updateByPrimaryKeySelective(sysUser);
        }
    }
    /**
     * @Author hyp
     * @Description 查询已分配用户角色列表
     * @Date 2023/10/26 14:33
     * @Return com.zhuiyun.project.common.response.CommonResult
     * @param pageRequest
     * @param user
     */
    @Override
    public PageResult selectAllocatedList(PageRequest pageRequest, SysUser user) {
        MybatisPageHelper.startPage(pageRequest);
        List<SysUser> users = userMapper.selectAllocatedList(user);
        List<SysUser> users1 = userMapper.listUsers(new SysUser());

        for (SysUser sysUser : users1) {
            for (SysUser user1 : users) {
                if (user1.getId().longValue() == sysUser.getId().longValue()){
                    sysUser.setFlag(true);
                    break;
                }
            }
        }


        PageResult pageResult = MybatisPageHelper.getPageResult(users1);

        return pageResult;
    }
    /**
     * @Author hyp
     * @Description 查询未分配用户角色列表
     * @Date 2023/10/26 14:33
     * @Return com.zhuiyun.project.common.response.CommonResult
     * @param pageRequest
     * @param user
     */
    @Override
    public PageResult selectUnallocatedList(PageRequest pageRequest, SysUser user) {
        MybatisPageHelper.startPage(pageRequest);
        List<SysUser> users = userMapper.selectUnallocatedList(user);
        PageResult pageResult = MybatisPageHelper.getPageResult(users);
        return pageResult;
    }

    /**
     * @Author hyp
     * @Description 用户分配角色
     * @Date 2023/11/3 8:26
     * @Return com.zhuiyun.project.common.response.CommonResult
     * @param userId
     * @param roleIds
     */
    @Override
    @Transactional
    public int addAuthRole(Integer userId, Long[] roleIds) {
        int i =userRoleMapper.deleteUserRoleByUserId(userId);
        insertUserRole(userId,roleIds);
        return i;
    }
    /**
     * @Author hyp
     * @Description 添加用户
     * @Date 2023/10/30 9:24
     * @Return com.zhuiyun.project.common.response.CommonResult
     * @param user
     */
    @Override
    public int addUser(SysUser user) {
        user.setCreateBy(SecurityUtils.getLoginName());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        int i = userMapper.addUser(user);
        insertUserRole(user);

        return i;
    }
    /**
     * @Author hyp
     * @Description 重置密码
     * @Date 2023/11/3 8:26
     * @Return com.zhuiyun.project.common.response.CommonResult
     * @param user
     */
    @Override
    public int resetPwd(SysUser user) {
        String newPassword = "sgf123456";
        SysUser loginUser = SecurityUtils.getLoginUser();
        if (user.getId().longValue() == loginUser.getId().longValue()){
            loginUser.setPassword(SecurityUtils.encryptPassword(newPassword));
            String token = (String) RedisUtil.get(loginUser.getLoginName());
            RedisUtil.set(token,loginUser, JWTConfig.expiration);
        }
        user.setPassword(SecurityUtils.encryptPassword(newPassword));
        return userMapper.editUser(user);
    }

    /**
      * @Author hyp
      * @Description 新增用户角色信息
      * @Date 2023/10/30 19:03
      * @Return void
      * @param user
    */
    private void insertUserRole(SysUser user) {
        this.insertUserRole(user.getId(), user.getRoleIds());
    }

    /**
      * @Author hyp
      * @Description 新增用户角色信息
      * @Date 2023/10/30 19:03
      * @Return void
      * @param userId
      * @param roleIds
    */

    public void insertUserRole(Integer userId, Long[] roleIds)
    {
        if (StringUtils.isNotEmpty(roleIds))
        {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>(roleIds.length);
            for (Long roleId : roleIds)
            {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(Long.valueOf(userId));
                ur.setRoleId(roleId);
                list.add(ur);
            }
            userRoleMapper.batchUserRole(list);
        }
    }
}
